package org.yzh.web.business.utils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class DateTimeUtils {

    /**
     * 时间字符串 to 时间戳——线程安全的
     *
     * @param datetimeStr 时间字符串形式
     * @param pattern     yyyyMMddHHmmss
     * @return 时间戳
     */
    public static long toTimestamp(String datetimeStr, String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime localDateTime = LocalDateTime.parse(datetimeStr, formatter);
        return localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    }

    /**
     * 时间戳 to 字符串——线程安全的
     *
     * @param timestamp 时间戳
     * @param pattern   yyyyMMddHHmmss
     * @return 时间字符串形式
     */
    public static String toDatetimeStr(long timestamp, String pattern) {
        LocalDateTime dateTime = LocalDateTime.ofEpochSecond(timestamp / 1000L, 0, ZoneOffset.ofHours(8));
        return dateTime.format(DateTimeFormatter.ofPattern(pattern));
    }

}
